<?php

/*
 * litchicms
 * Copyright (C) 2010-6-22 Author: tiefa(539247@qq.com)
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
!defined('BRK') && exit("!");

//允许的文件类型
$BRK_GLOBAL['attachment_type'] = array(
    "image/jpeg" => '.jpg',
    "image/pjpeg" => '.jpg',
    "image/gif" => '.gif',
    "image/x-png" => '.png',
    "image/png" => '.png',
    "text/plain" => '.attach',
    "application/x-shockwave-flash" => '.attach',
    "application/octet-stream" => '.attach',
);
//允许的后缀名
$BRK_GLOBAL['attachment_suffix'] = array(
    '.jpeg', '.jpg', '.gif', '.png', '.rar', '.zip'
);


$BRK_GLOBAL['attach_path'] = "data/tt/" . ($BRK_GLOBAL['datearray']['year'] - 2000) . "/" . $BRK_GLOBAL['datearray']['mon'];
check_make_dir($BRK_GLOBAL['filesavepath'] = BRK . $BRK_GLOBAL['attach_path']);

/*
 * 移动上传来的文件至相应目录
 */

function attachment_move($filearr) {
    global $BRK_GLOBAL, $BRK_SET;

    $filearr['private_or_public'] = empty($filearr['private_or_public']) ? 0 : 1;
    $filearr['attachment_description'] = empty($filearr['attachment_description']) ? $filearr['name'] : $filearr['attachment_description'];

    $temp = array();
    $temp['re'] = FALSE;
    $temp['name'] = $filearr['name'];

    if ($filearr['error'] != 0) {
        $temp['error'] = '上传失败';
        return $temp;
    }

    if (!key_exists($filearr['type'], $BRK_GLOBAL['attachment_type'])) {
        $temp['error'] = '不在允许的上传类型内';
        return $temp;
    }

    if (empty($filearr['suffix'])) {
        $filearr['suffix'] = $BRK_GLOBAL['attachment_type'][$filearr['type']];
    } else {
        if (!in_array($filearr['suffix'], $BRK_GLOBAL['attachment_suffix'])) {
            $temp['error'] = '不在允许的上传类型内';
            return $temp;
        }
    }

    $filearr['sys_suffix'] = $BRK_GLOBAL['attachment_type'][$filearr['type']];

    $filesavename = rand_file_name($BRK_GLOBAL['datearray'][0], $filearr['sys_suffix'], $BRK_GLOBAL['filesavepath']);

    if (is_uploaded_file($filearr['tmp_name'])) {
        if (move_uploaded_file($filearr['tmp_name'], $BRK_GLOBAL['filesavepath'] . '/' . $filesavename)) {
            $temp['re'] = TRUE;
            $temp['savsename'] = $filesavename;
            $temp['dataarr'] = array(
                'attach_type' => $filearr['suffix'],
                'attach_sys_name' => $filesavename,
                'attach_name' => $filearr['attachment_description'],
                'attach_time' => $BRK_GLOBAL['datearray'][0],
                'attach_user' => $_SESSION['brk_login']['user_id'],
                'attach_isimg' => $filearr['sys_suffix'] == '.attach' ? 0 : 1,
                'attach_size' => $filearr['size'],
                'attach_path' => $BRK_GLOBAL['attach_path'] . '/' . $filesavename,
                'attach_sys_thumb' => $filearr['sys_suffix'] == '.attach' ? 'data/sys/attach_40_40.jpg' : attachment_thumb($BRK_GLOBAL['filesavepath'] . '/' . $filesavename),
                'attach_thumb' => $filearr['sys_suffix'] == '.attach' ? 'data/sys/attach_20_20.jpg' : attachment_thumb($BRK_GLOBAL['filesavepath'] . '/' . $filesavename, $BRK_SET['thumbnail_w'], $BRK_SET['thumbnail_h']),
                'attach_click' => 0,
                'attach_right' => $filearr['private_or_public'],
                'attach_sys_suffix' => $filearr['sys_suffix']
            );

            if ($temp['dataarr']['attach_id'] = brk_insert('attachment', $temp['dataarr'])) {
                if (!empty($GLOBALS['COLLECTION_ID']) && !empty($GLOBALS['RECORD_ID'])) {
                    $insertINcoll = array(
                        'attach_id' => $temp['dataarr']['attach_id'],
                        'collection_id' => $GLOBALS['COLLECTION_ID'],
                        'data_id' => $GLOBALS['RECORD_ID']
                    );
                    brk_insert('attach_relationships', $insertINcoll);
                } else {
                    //公共附件
                }
                $temp['dataarr']['attach_name'] = stripslashes($temp['dataarr']['attach_name']);
                return $temp;
            }
        }
    }

    $temp['error'] = '!TODO:检查程序';
    return $temp;
}

//组装保存的文件名
function rand_file_name($i, $ii, $iii) {
    $temp = $i . rand(10000, 99999) . $ii;
    if (is_file($iii . '/' . $temp)) {
        return rand_file_name($i, $ii, $iii);
    } else {
        return $temp;
    }
}

//缩略图  //$mustUseSet 强制大小?
function attachment_thumb($file, $to_w="40", $to_h = "40", $mustUseSet=FALSE) {
    $fileinfo = pathinfo($file);
    //TODO: 检测老版本PHP是否含有 $fileinfo['filename']
    $fun = "imagecreatefrom";
    switch ($fileinfo['extension']) {
        case 'gif':
            return str_replace(BRK, "", $file);
            break;
        case 'jpg':
            $fun.='jpeg';
            break;
        case 'jpeg':
            $fun.='jpeg';
            break;
        case 'png':
            $fun.='png';
            break;
        default :
            return $file;
            break;
    }

    $image_lod = call_user_func($fun, $file);
    list($old_w, $old_h) = getimagesize($file);


    $new_w = $new_h = 0;

    if ($mustUseSet) {
        $new_w = $to_w;
        $new_h = $to_h;
    } else {
        if ($old_w <= $to_w && $old_h <= $to_h) {
            $new_w = $old_w;
            $new_h = $old_h;
        } else {
            $XY_z = min($to_w / $old_w, $to_h / $old_h);
            $new_w = $old_w * $XY_z;
            $new_h = $old_h * $XY_z;
        }
    }



    $file_image_thumb = $fileinfo['dirname'] . '/' . $fileinfo['filename'] . "_{$to_w}_{$to_h}.jpg";

    $image_thumb = imagecreatetruecolor($new_w, $new_h);
    imagecopyresized($image_thumb, $image_lod, 0, 0, 0, 0, $new_w, $new_h, $old_w, $old_h);

    imagejpeg($image_thumb, $file_image_thumb, 100);

    return str_replace(BRK, "", $file_image_thumb);
}

//图片裁切 结果会覆盖原图片
function attachment_cut($file, $to_w=0, $to_h = 0, $left=0, $top=0) {
    if (!is_file($file)) {
        return false;
    }
    $fileinfo = pathinfo($file);
    $fun = "imagecreatefrom";
    switch ($fileinfo['extension']) {
        case 'gif':
            return str_replace(BRK, "", $file);
            break;
        case 'jpg':
            $fun.='jpeg';
            break;
        case 'jpeg':
            $fun.='jpeg';
            break;
        case 'png':
            $fun.='png';
            break;
        default :
            return $file;
            break;
    }

    $image_lod = call_user_func($fun, $file);
    list($old_w, $old_h) = getimagesize($file);

    if ($old_w <= $to_w || $old_h <= $to_h) {
        return $file;
    }


    $image_cut = imagecreatetruecolor($to_w, $to_h);

    imagecopy($image_cut, $image_lod, 0, 0, $left, $top, $to_w, $to_h);

    imagejpeg($image_cut, $file, 100);

    return $file;
}

//判断是否有操作某个附件的权限
if (!function_exists('Component_attachment_action_rigth')) {

    function Component_attachment_action_rigth($id) {

        ob_header_char();
        if (empty($id)) {
            echo json_encode(array('status' => FALSE));
            exit;
        }
        $one = brk_select_one('attachment', '*', "WHERE attach_id=" . intval($id));
        //TODO  : 判断权限 1是否自己传的? 2不是 那么自己所在组是否有权限
        $right = FALSE;
        $right = TRUE;
        if ($right) {
            return $one;
        } else {
            echo json_encode(array('status' => FALSE, 'error' => '没权限'));
            exit;
        }
    }

}
